package com.gitee.feizns.quickstart.jackson.module;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.gitee.feizns.dynamic.Strings;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * 当地日期时间序列化器
 * @author feizns
 * @since 2023/07/13
 */
@NoArgsConstructor
public class Java8TimeSerializer extends JsonSerializer<TemporalAccessor> {

    /**
     * 格式
     */
    private DateTimeFormatter formatter;

    /**
     * 当地日期时间序列化器
     * @param format 格式
     */
    public Java8TimeSerializer(String format) {
        this.formatter = Strings.hasText(format) ? DateTimeFormatter.ofPattern(format) : null;
    }

    @Override
    public void serialize(TemporalAccessor value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        //格式化时间
        String stringTime = formatter != null ? formatter.format(value): value.toString();
        gen.writeString(stringTime);
    }

}